'use strict';

const path = require('path');
const fs = require('fs');
const yaml = require('js-yaml');

const store = {};

/**
 * 读取目录
 * @param {string} parentPath 目录路径
 * @param {string} parentDomain ID域（namespace)
 */
function readPath(parentPath, parentDomain) {
  const dir = fs.readdirSync(parentPath);
  dir.forEach(child => {
    const childPath = path.resolve(parentPath, child);
    const stat = fs.statSync(childPath);
    if (stat.isDirectory()) {
      const childDomain = parentDomain ? (parentDomain + '.' + child) : child;
      readPath(childPath, childDomain);
    } else {
      const filename = child.substr(0, child.length - 4);
      const childDomain = parentDomain ? (parentDomain + '.' + filename) : filename;
      readFile(childPath, childDomain);
    }
  });
}

/**
 * 读取域
 * @param {string} [domain] ID域，可以到目录或文件
 */
function readDomain(domain = '') {
  const subpath = domain.replace('.', '/');
  const realpath = path.join(__dirname, '../sql', subpath);
  const realfile = realpath + '.yml';
  if (fs.existsSync(realpath)) {
    readPath(realpath, '');
  } else if (fs.existsSync(realfile)) {
    readFile(realfile, domain);
  }
}

/**
 * 读取文件
 * @param {string} file 文件路径
 * @param {string} domain ID域（namespace)
 */
function readFile(file, domain) {
  try {
    console.log('read sql file: ' + file);
    const doc = yaml.load(fs.readFileSync(file, 'utf-8'));
    Object.keys(doc).forEach(key => {
      const id = domain + '.' + key;
      const obj = doc[key];
      if (obj) {
        if (typeof obj === 'string') {
          store[id] = {
            ds: null,
            sql: obj,
          };
        } else {
          store[id] = {
            ds: obj.ds,
            sql: obj.sql,
          };
        }
      }
    });
  } catch (e) {
    console.log('read sql file error: ' + file);
    console.log(e);
  }
}

/**
 * 读取SQL配置
 * @param {string} id SQL ID
 */
function readSql(id) {
  const arr = id.split('.');
  arr.pop();
  const domain = arr.join('.');
  const file = path.join(__dirname, '../sql', arr.join('/')) + '.yml';
  readFile(file, domain);
  return store[id];
}

/**
 * 加载SQL配置
 * @param {string} id SQL ID
 */
function load(id) {
  let sql = store[id];
  if (!sql) {
    sql = readSql(id);
  }
  return sql;
}

module.exports = { load, readDomain };
